/* eslint-disable prettier/prettier */

import { Vector3 } from 'three'
import { camera, controls } from './scene.js'
import Quadtree from 'quadtree-lib'

let canUpdate = true

// 节流函数
const throttle = (func, delay) => {
  let lastCall = 0
  return function (...args) {
    const now = new Date().getTime()
    if (now - lastCall < delay) {
      return
    }
    lastCall = now
    return func(...args)
  }
}

// 初始化四叉树
const quadtree = new Quadtree({
  width: window.innerWidth,
  height: window.innerHeight
})

// 主函数，处理精灵组
const forGroupArray = spriteGroup => {
  if (canUpdate) {
    canUpdate = false

    // 清空四叉树
    quadtree.clear()

    // 将所有精灵插入四叉树
    spriteGroup.children.forEach(sprite => {
      const screenCoords = getScreenCoords(sprite)
      sprite.visible = true
      quadtree.insert({
        x: screenCoords.x,
        y: screenCoords.y,
        width: screenCoords.width,
        height: screenCoords.height,
        sprite
      })
    })

    // 检查并隐藏重叠的精灵
    spriteGroup.children.forEach(sprite => {
      const screenCoords = getScreenCoords(sprite)
      const candidates = quadtree.retrieve({
        x: screenCoords.x,
        y: screenCoords.y,
        width: screenCoords.width,
        height: screenCoords.height
      })

      candidates.forEach(candidate => {
        if (candidate.sprite !== sprite) {
          checkAndHideSprites(sprite, candidate.sprite, screenCoords, candidate)
        }
      })
    })

    // 定时重新计算
    setTimeout(() => {
      canUpdate = true
    }, 1000)
  }
}

// 获取精灵的屏幕坐标和大小
const getScreenCoords = sprite => {
  const worldVector = new Vector3(sprite.position.x, sprite.position.y, sprite.position.z)
  const standardVector = worldVector.project(camera)
  const winWidth = window.innerWidth
  const winHeight = window.innerHeight
  const halfWidth = winWidth / 2
  const halfHeight = winHeight / 2

  const x = Math.round(standardVector.x * halfWidth + halfWidth)
  const y = Math.round(-standardVector.y * halfHeight + halfHeight) - 30
  const width = 100
  const height = 40

  return { x, y, width, height }
}

// 检查两个精灵是否重叠，并隐藏距离较远的一个
const checkAndHideSprites = (sprite1, sprite2, coords1, coords2) => {
  if (coords1.x + coords1.width > coords2.x && coords2.x + coords2.width > coords1.x && coords1.y + coords1.height > coords2.y && coords2.y + coords2.height > coords1.y) {
    const distance1 = sprite1.position.distanceTo(camera.position)
    const distance2 = sprite2.position.distanceTo(camera.position)

    if (distance1 > distance2) {
      sprite1.visible = false
    } else {
      sprite2.visible = false
    }
  }
}


export { forGroupArray }
